package image;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.net.HttpRequest;
import lombok.Data;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import util.HttpUtil;
import util.ImageUtil;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author tangfudong
 * @date 2020/10/26
 */
@Slf4j
public class LoadImg {
    public static void main(String[] args) {
        // 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
        // 写法1：
        String fileName =  "C:\\Users\\20804034\\Desktop\\点问\\1102\\S5 Pro.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(fileName, ExcelModel.class, new DemoDataListener()).sheet().doRead();

    }

    public static class DemoDataListener extends AnalysisEventListener<ExcelModel> {

        @Override
        public void invoke(ExcelModel excelModel, AnalysisContext analysisContext) {
            try {
                int flag = 0;
                String[] split = excelModel.getQuestionPicUrl().split("_");
                String encode = ImageUtil.getImageBase64StrFromUrl(excelModel.getQuestionPicUrl());
                JSONObject jsObj = new JSONObject();
                jsObj.put("x",Integer.parseInt(split[split.length-3]));
                jsObj.put("y", Integer.parseInt(split[split.length-2]));
                jsObj.put("img", encode);
                jsObj.put("img_name", "src.jpg");
                jsObj.put("type","box");
                String post = HttpUtil.post("http://1341757520627356.cn-beijing.pai-eas.aliyuncs.com/api/predict/xtc_ocr4_0_web", jsObj.toJSONString());
                System.out.println(post);
                JSONObject jsonObject = JSON.parseObject(post);
                JSONObject jsonData = jsonObject.getJSONObject("data");
                JSONArray regions = jsonData.getJSONArray("regions");
                for (int i = 0; i < regions.size(); i++) {
                    JSONArray lines = regions.getJSONObject(i).getJSONArray("lines");
                    for (int j = 0; j < lines.size(); j++) {
                        JSONArray slices = lines.getJSONObject(j).getJSONArray("slices");
                        for (int k = 0; k < slices.size(); k++) {
                            JSONObject slicesJSONObject = slices.getJSONObject(k);
                            String type = slicesJSONObject.getString("type");
                            String text = slicesJSONObject.getString("text");
                            if("formula".equals(type)){
                                if(text.contains("times")
                                        ||text.contains("div")
                                        ||text.contains("+")
                                        ||text.contains("-")
                                        ||text.contains("=")
                                        ||text.contains("×")
                                ){
                                    flag++;
                                    System.err.println(slicesJSONObject.toJSONString());
                                }else {
                                    System.out.println(slicesJSONObject.toJSONString());
                                }
                            }
                        }
                    }
                }

                if(flag > 2) {
                    ImageUtil.loadImg(excelModel.getPhotographImg(), "D:\\share\\点问现网\\s5p\\");
                }else {
                    ImageUtil.loadImg(excelModel.getPhotographImg(), "D:\\share\\点问现网\\s5p-bad\\");
                }
                //log.info("处理成功:{}",JSONObject.toJSONString(excelModel));
            }catch (Exception e){
                System.out.println("下载图片异常：{}"+JSONObject.toJSONString(excelModel));
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            System.out.println("处理完成");
        }
    }

    @Data
    public static class ExcelModel{
        @ExcelProperty(value = "photograph_img")
        private String photographImg;
        @ExcelProperty(value = "ocr_content")
        private String ocrContent;
        @ExcelProperty(value = "question_pic_url")
        private String questionPicUrl;
        @ExcelProperty(value = "pointXY")
        private String pointXY;
    }

    /**
     * 获取内容中-汉字个数(去重后)
     * @param content - 内容
     * @return int
     */
    public static int getChineseSize(String content) {
        //汉字数量
        if (content == null) {
            return 0;
        }
        java.util.List<String> asList = new ArrayList<>();
        for (char c : content.toCharArray()) {
            asList.add(String.valueOf(c));
        }
        StringBuilder sb = new StringBuilder();
        List<String> collect = asList.stream().distinct().collect(Collectors.toList());
        collect.forEach(sb::append);
        int count = 0;
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(sb);
        int len = m.groupCount();
        while (m.find()) {
            for (int i = 0; i <= len; i++) {
                count = count + 1;
            }
        }
        return count;
    }

    /**
     * 获取内容中-汉字个数(去重后)
     * @param content - 内容
     * @return int
     */
    public static int getNumSize(String content) {
        //汉字数量
        if (content == null) {
            return 0;
        }
        int count = 0;
        String regEx = "[0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(content);
        int len = m.groupCount();
        while (m.find()) {
            for (int i = 0; i <= len; i++) {
                count = count + 1;
            }
        }
        return count;
    }

    /**
     * 获取内容中-汉字个数(去重后)
     * @param content - 内容
     * @return int
     */
    public static int getEnSize(String content) {
        //汉字数量
        if (content == null) {
            return 0;
        }
        int count = 0;
        String regEx = "[a-zA-z]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(content);
        int len = m.groupCount();
        while (m.find()) {
            for (int i = 0; i <= len; i++) {
                count = count + 1;
            }
        }
        return count;
    }

    public static byte[] inputStream2byte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }


}
